package hh.Servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


import jdk.internal.org.objectweb.asm.commons.SerialVersionUIDAdder;

/**
 * Servlet implementation class MultiRegisterServlet
 */
@WebServlet("/Muform")
@MultipartConfig(location="/Users/hh/myblogs/uploads", maxRequestSize=10485760 )
public class MultiRegisterServlet extends HttpServlet {
	
	private static final long SerialVersionUIDAdder = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String contextPath = request.getServletContext().getRealPath("/uploads");
		File uploadDir = new File(contextPath);
		if(!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		
		
		Part filePart = request.getPart("file");
		String filename = filePart.getSubmittedFileName();
		String extName = filename.substring(filename.lastIndexOf("."));
		if (!extName.equalsIgnoreCase(".jpg") && !extName.equalsIgnoreCase(".png")) {
			throw new ServletException("Not supported image type.");
		}
		String diskFilename = System.currentTimeMillis() + extName;
		String diskFile =contextPath + File.separator + diskFilename;
		filePart.write(diskFile);
		Map<String, String> map = new HashMap<>();
		for(Part part : request.getParts()) {
			if (part.getName().equals("file")) 
				continue;
			String content = getContent(part);
			String key = part.getName();
			if (map.get(key) == null) {
				map.put(key,content);
			}else {
				String newValue = map.get(key) + "," + content;
				map.put(key,newValue);
				
			}
		}
		response.sendRedirect("./uploads/" + diskFilename);
		
	
	}
	private String getContent(Part part) throws IOException {
		try(Scanner scanner = new Scanner(part.getInputStream())){
			return scanner.next();
		}
		
	}

}
